import http from '@ohos.net.http';
import dataStorage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility';


export default class Request {
    #baseUrl = "https://yeziji.xyz/forum";
    #url;
    #header;
    result;

    constructor(url, header) {
        // 判断是否为完整地址
        if (url[0] === '/') {
            this.#url = `${this.#baseUrl}${url}`;
        } else {
            this.#url = `${this.#baseUrl}/${url}`;
        }
        // 自定义请求头
        if (header) {
            this.#header = header;
        }
    }

    static build(url, header) {
        return new Request(url, header);
    }

    customer (baseUrl) {
        if (baseUrl) {
            this.#baseUrl = baseUrl;
        }
        return this;
    }

    #validate = () => {
        if (!this.#url) {
            console.error("地址获取失败");
            return false;
        }
        return true;
    }
    /**
     * 获取 token
     *
     * <p> 由于做了 JSON#stringify 的处理，因此保存的数据并不是普通的字符串，所以要做 replace 处理
     */
    #getToken = async () => {
        let path = await featureAbility.getContext().getFilesDir();
        let storage = dataStorage.getStorageSync(path + '/user')
        // 此处 token 可能是个对象，因此用 JSON#stringify 强行转 string 否则无法存储
        let token = storage.getSync('token', 'Token is empty');
        if (token != 'Token is empty') {
            token = token.replace('[', '').replace(']', '').replace('"', '').replace('"', '');
        }
        return token;
    }

    /**
     * 发送 request 请求
     *
     * @param url 请求地址
     * @param method 请求方法
     * @param data 请求参数
     * @param header 请求头
     */
    #request = async (url, method, data, header) => {
        let httpRequest = http.createHttp();
        // 判断是否自定义了请求头
        if (!header) {
            header = {
                'Content-Type': 'application/json'
            }
        } else {
            if (!header['Content-Type']) {
                header['Content-Type'] = 'application/json';
            }
        }
        let token = await this.#getToken();
        if (token != 'Token is empty') {
            header['Authorization'] = token;
        }
        return new Promise((resolve, reject) => {
            httpRequest.request(url, {
                method: method,
                extraData: data,
                header: header
            }, (error, data) => {
                if (!error) {
                    resolve(data);
                } else {
                    reject(error);
                }
            })
        })
    }

    /**
     * get 请求
     */
    async get(data) {
        if (this.#validate()) {
            this.result = await this.#request(this.#url, http.RequestMethod.GET, data, this.#header);
        }
        return this;
    }

    /**
     * post 请求
     */
    async post(data) {
        if (this.#validate()) {
            this.result = await this.#request(this.#url, http.RequestMethod.POST, data, this.#header);
        }
        return this;
    }

    getData() {
        return this.result.result;
    }

    getResCode() {
        return this.result.responseCode;
    }

    getHeader() {
        return this.result.header;
    }

    getCookies() {
        return this.result.cookies;
    }
}

